package com.tudouji.project.repository.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.tudouji.common.utils.AccountDate;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.project.bill.domain.Whinformitem;
import com.tudouji.project.bill.domain.Whoutformitem;
import com.tudouji.project.bill.mapper.WhinformitemMapper;
import com.tudouji.project.bill.mapper.WhoutformitemMapper;
import com.tudouji.project.bill.service.impl.WhinformitemServiceImpl;
import com.tudouji.project.produce.domain.Scrapapply;
import com.tudouji.project.produce.domain.Scrapapplyitem;
import com.tudouji.project.produce.mapper.ScrapapplyMapper;
import com.tudouji.project.produce.mapper.ScrapapplyitemMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.repository.mapper.RptStoreanalysisMapper;
import com.tudouji.project.repository.domain.RptStoreanalysis;
import com.tudouji.project.repository.service.IRptStoreanalysisService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 动态库存Service业务层处理
 * 
 * @author tudouji
 * @date 2021-05-13
 */
@Service
public class RptStoreanalysisServiceImpl implements IRptStoreanalysisService 
{
    @Autowired
    private RptStoreanalysisMapper rptStoreanalysisMapper;
    @Autowired
    private WhinformitemMapper whinformitemMapper;
    @Autowired
    private WhoutformitemMapper whoutformitemMapper;
    @Autowired
    private ScrapapplyMapper scrapapplyMapper;
    @Autowired
    private ScrapapplyitemMapper scrapapplyitemMapper;

    /**
     * 查询动态库存
     * 
     * @param guid 动态库存ID
     * @return 动态库存
     */
    @Override
    public RptStoreanalysis selectRptStoreanalysisById(String guid)
    {
        return rptStoreanalysisMapper.selectRptStoreanalysisById(guid);
    }

    /**
     * 查询动态库存列表
     * 
     * @param rptStoreanalysis 动态库存
     * @return 动态库存
     */
    @Override
    public List<RptStoreanalysis> selectRptStoreanalysisList(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.selectRptStoreanalysisList(rptStoreanalysis);
    }

    /**
     * 新增动态库存
     * 
     * @param rptStoreanalysis 动态库存
     * @return 结果
     */
    @Override
    public int insertRptStoreanalysis(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.insertRptStoreanalysis(rptStoreanalysis);
    }

    /**
     * 修改动态库存
     * 
     * @param rptStoreanalysis 动态库存
     * @return 结果
     */
    @Override
    public int updateRptStoreanalysis(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.updateRptStoreanalysis(rptStoreanalysis);
    }

    /**
     * 批量删除动态库存
     * 
     * @param guids 需要删除的动态库存ID
     * @return 结果
     */
    @Override
    public int deleteRptStoreanalysisByIds(String[] guids)
    {
        return rptStoreanalysisMapper.deleteRptStoreanalysisByIds(guids);
    }

    /**
     * 删除动态库存信息
     * 
     * @param guid 动态库存ID
     * @return 结果
     */
    @Override
    public int deleteRptStoreanalysisById(String guid)
    {
        return rptStoreanalysisMapper.deleteRptStoreanalysisById(guid);
    }
    @Override
    public List<RptStoreanalysis> findRPT(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.findRPT(rptStoreanalysis);
    }
    @Override
    public RptStoreanalysis findRPTSUM(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.findRPTSUM(rptStoreanalysis);
    }
    @Override
    public List<RptStoreanalysis> findRPTByDay(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.findRPTByDay(rptStoreanalysis);
    }
    @Override
    public RptStoreanalysis findRPTByDaySUM(RptStoreanalysis rptStoreanalysis)
    {
        return rptStoreanalysisMapper.findRPTByDaySUM(rptStoreanalysis);
    }

    @Transactional
    public void recoverRptAnalysis(String starttime, String endtime) throws Exception{
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dates = AccountDate.getEveryday(starttime, endtime);
        for (int i = 0; i < dates.size(); i++) {
            String nowDate = dates.get(i);
            if (StringUtils.isNotBlank(nowDate)) {
                deleteToday(simpleDate.parse(nowDate));
                rpt(simpleDate.parse(nowDate));
            }
        }
    }


    /**
     * 删除当天数据
     *
     * @param today
     * @throws Exception
     */
    public void deleteToday(Date today){
        RptStoreanalysis rpt = new RptStoreanalysis();
        rpt.setRptdate(today);
        List<RptStoreanalysis> rpts = this.selectRptStoreanalysisList(rpt);
        for (RptStoreanalysis item : rpts) {
            this.deleteRptStoreanalysisById(item.getGuid());
        }
    }

    /**
     * 统计主程
     * `whintype` int(4) NOT NULL COMMENT
     * '1、采收入库2、调拨入库 3,采购入库 ,4 产成品入库,5不合格入库6退料入库7调整入库'
     * `Outtype` int(4) NOT NULL COMMENT
     * '1.采购单出库2.销售单出库3.调拨出库4.领料出库5.报废出库6调整出库'
     */
    public void rpt(Date findDate){
        int[] w1 = new int[]{1, 9};
        int[] w2 = new int[]{4, 5};
        int[] w3 = new int[]{6, 8};
        int[] w4 = new int[]{2};
        int[] w5 = new int[]{7};
        setDataWhin(findDate, w1, 1);
        setDataWhin(findDate, w2, 2);
        setDataWhin(findDate, w3, 3);
        setDataWhin(findDate, w4, 4);
        setDataWhin(findDate, w5, 5);

        setDataWhout(findDate, 4, 6);
        setDataWhout(findDate, 2, 8);
        setDataWhout(findDate, 3, 9);
        setDataWhout(findDate, 6, 10);

        List<Scrapapply> scraps = getDataScraptype(findDate);
        if (scraps.size() > 0) {
            for (int i = 0; i < scraps.size(); i++) {
                Scrapapply type = scraps.get(i);
                List<Scrapapply> scrapsType = getDataScrap(findDate, type.getOrgguid(), type.getSrguid());
                List<Scrapapply> scraptypeFindListProduce = new ArrayList<>();
                List<Scrapapply> scraptypeFindListOneL = new ArrayList<>();
                List<Scrapapply> scraptypeFindListOne = new ArrayList<>();
                List<Scrapapply> scraptypeFindListTwoL = new ArrayList<>();
                List<Scrapapply> scraptypeFindListTwo = new ArrayList<>();
                for (int j = 0; j < scrapsType.size(); j++) {
                    Scrapapply scrapapply = scrapsType.get(j);
                    if (null != scrapapply){
                        if (3 == scrapapply.getType()) {//查的是报废明细
                            scraptypeFindListProduce.add(scrapapply);
                        }
                    /*if (3 == scrapsType.get(j).getType()
                            && 1 == scrapsType.get(j).getScraptype()) {//查的是报废明细
                        scraptypeFindListOneL.add(scrapsType.get(j));
                    }*/
                        if (3 == scrapapply.getType()
                                && 2 == (scrapapply.getScraptype() == null ? 0:scrapapply.getScraptype())) {//查的是报废明细
                            scraptypeFindListTwoL.add(scrapapply);
                        }
                        if ((1 == scrapapply.getType() || 2 == scrapapply.getType())
                                && 1 == (scrapapply.getScraptype() == null ? 0:scrapapply.getScraptype())) {//查的是出库单
                            scraptypeFindListOne.add(scrapapply);
                        }
                        if ((1 == scrapapply.getType() || 2 == scrapapply.getType())
                                && 2 == (scrapapply.getScraptype() == null ? 0:scrapapply.getScraptype())) {//查的是出库单
                            scraptypeFindListTwo.add(scrapapply);
                        }
                    }
                }
                String[] scrapFind = new String[scraptypeFindListProduce.size()];
//                String[] scraptypeFindOneL = new String[scraptypeFindListOneL.size()];
                String[] scraptypeFindOne = new String[scraptypeFindListOne.size()];
                String[] scraptypeFindTwoL = new String[scraptypeFindListTwoL.size()];
                String[] scraptypeFindTwo = new String[scraptypeFindListTwo.size()];
                if (scrapFind.length > 0) {
                    for (int j = 0; j < scraptypeFindListProduce.size(); j++) {
                        scrapFind[j] = scraptypeFindListProduce.get(j).getGuid();
                    }
                    setDataScrapitem(scrapFind, type.getOrgguid(), type.getSrguid(), type.getOrgname(), type.getStrname()
                            , findDate, 7);
                }
                //损耗和腐烂从报废明细和出库单中加起来

                /*if (scraptypeFindOneL.length > 0) {
                    for (int j = 0; j < scraptypeFindListOneL.size(); j++) {
                        scraptypeFindOneL[j] = scraptypeFindListOneL.get(j).getGuid();
                    }
                    setDataScrapitemL(scraptypeFindOneL, type.getOrgguid(), type.getSrguid(), type.getOrgname(), type.getStrname()
                            , findDate, 11);
                }*/
                if (scraptypeFindTwoL.length > 0) {
                    for (int j = 0; j < scraptypeFindListTwoL.size(); j++) {
                        scraptypeFindTwoL[j] = scraptypeFindListTwoL.get(j).getGuid();
                    }
                    setDataScrapitemL(scraptypeFindTwoL, type.getOrgguid(), type.getSrguid(), type.getOrgname(), type.getStrname()
                            , findDate, 12);
                }

                if (scraptypeFindOne.length > 0) {
                    for (int j = 0; j < scraptypeFindListOne.size(); j++) {
                        scraptypeFindOne[j] = scraptypeFindListOne.get(j).getGuid();
                    }
                    setDataBFWhout(scraptypeFindOne, findDate, 11);
                }
                if (scraptypeFindTwo.length > 0) {
                    for (int j = 0; j < scraptypeFindListTwo.size(); j++) {
                        scraptypeFindTwo[j] = scraptypeFindListTwo.get(j).getGuid();
                    }
                    setDataBFWhout(scraptypeFindTwo, findDate, 12);
                }
            }
        }

    }


    /**
     * 入库重量统计
     *
     * @param findDate
     * @param w1
     * @param type     1~5
     * @return
     * @throws Exception
     */
    private Whinformitem setDataWhin(Date findDate, int[] w1, int type) {
        Whinformitem witem = new Whinformitem();
        witem.setCreatedate(findDate);
        witem.setWhintype(w1);
        List<Whinformitem> items = whinformitemMapper.rpt_whin(witem);
        for (int i = 0; i < items.size(); i++) {
            Whinformitem item = items.get(i);
            if (null != item) {
                saveAndupdate(item.getOrgguid(), item.getSrguid(), item.getShrguid(), item.getProductguid()
                        , item.getSpguid(), findDate, type, item.getWeight(), item.getOrgname(), item.getRoom()
                        , item.getHouse(), item.getProduct(), item.getSpename(), 1, item.getStockunit(), item.getStockunitid());
            }
        }
        return witem;
    }

    /**
     * 出库重量统计
     *
     * @param findDate
     * @param w1
     * @param type     6-12
     * @return
     * @throws Exception
     */
    private Whoutformitem setDataWhout(Date findDate, int w1, int type) {
        Whoutformitem witem = new Whoutformitem();
        witem.setCreatedate(findDate);
        witem.setOuttype(w1);
        List<Whoutformitem> items = whoutformitemMapper.rpt_whout(witem);
        for (int i = 0; i < items.size(); i++) {
            Whoutformitem item = items.get(i);
            if (null != item) {
                saveAndupdate(item.getOrgguid(), item.getSrguid(), item.getShrguid(), item.getProductguid()
                        , item.getSpguid(), findDate, type, item.getWeight(), item.getOrgname(), item.getRoom()
                        , item.getHouse(), item.getProduct(), item.getSpename(), 1, item.getStockunit(), item.getStockunitid());
            }
        }
        return witem;
    }

    /**
     * 报废出库重量统计
     *
     * @param findDate
     * @param type     11,12
     * @return
     * @throws Exception
     */
    private Whoutformitem setDataBFWhout(String[] scrapapplyids, Date findDate, int type) {
        Whoutformitem witem = new Whoutformitem();
        witem.setOrderguids(scrapapplyids);
        List<Whoutformitem> items = whoutformitemMapper.rpt_whoutbf(witem);
        for (int i = 0; i < items.size(); i++) {
            Whoutformitem item = items.get(i);
            if (null != item) {
                saveAndupdate(item.getOrgguid(), item.getSrguid(), item.getShrguid(), item.getProductguid()
                        , item.getSpguid(), findDate, type, item.getWeight(), item.getOrgname(), item.getRoom()
                        , item.getHouse(), item.getProduct(), item.getSpename(), 2, item.getStockunit(), item.getStockunitid());
            }
        }
        return witem;
    }

    /**
     * 创建、更新
     *
     * @param orgguid
     * @param srguid
     * @param shguid
     * @param productid
     * @param specguid
     * @param rptdate
     * @param type      1~12
     *                  采收入库重量
     *                  生产入库重量
     *                  退料入库重量
     *                  调拨入库重量
     *                  调整入库重量
     *                  生产领料出库重量
     *                  生产报废重量
     *                  销售出库重量
     *                  调拨出库重量
     *                  调整出库重量
     *                  报废出库重量
     *                  报废出库重量
     * @param weight    对应type的重量
     * @param orgname
     * @param room
     * @param house
     * @param product
     * @param spename
     * @param spename   1:普通2：更新重量
     */
    public void saveAndupdate(String orgguid, String srguid, String shguid, String productid,
                              String specguid, Date rptdate, int type, BigDecimal weight,
                              String orgname, String room, String house, String product, String spename, int controlType
            , String stockunit, Long stockunitid)  {
        RptStoreanalysis rpt = new RptStoreanalysis();
        rpt.setCompanyid(orgguid);
        rpt.setSrguid(srguid);
        rpt.setShguid(shguid);
        rpt.setProductid(productid);
        rpt.setSpecid(specguid);
        rpt.setRptdate(rptdate);
        List<RptStoreanalysis> rpts = rptStoreanalysisMapper.selectRptStoreanalysisList(rpt);
        if (rpts.size() > 0) {
            rpt = rpts.get(0);
        }
        if (1 == type) {
            rpt.setBuyinweight(weight);
        }
        if (2 == type) {
            rpt.setProdinweight(weight);
        }
        if (3 == type) {
            rpt.setRetinweight(weight);
        }
        if (4 == type) {
            rpt.setTransinweight(weight);
        }
        if (5 == type) {
            rpt.setAdjinweight(weight);
        }
        if (6 == type) {
            rpt.setPickoutweight(weight);
        }
        if (7 == type) {
            rpt.setPscrapweight(weight);
        }
        if (8 == type) {
            rpt.setSelloutweight(weight);
        }
        if (9 == type) {
            rpt.setTransoutweight(weight);
        }
        if (10 == type) {
            rpt.setAdjoutweight(weight);
        }
        if (11 == type && 1 == controlType) {
            rpt.setScrbadoutweight(weight);
        }
        if (11 == type && 2 == controlType) {
            rpt.setScrbadoutweight((rpt.getScrbadoutweight() == null ? BigDecimal.ZERO : rpt.getScrbadoutweight()).add(weight));
        }
        if (12 == type && 1 == controlType) {
            rpt.setScrlostoutweight(weight);
        }
        if (12 == type && 2 == controlType) {
            rpt.setScrlostoutweight((rpt.getScrlostoutweight() == null ? BigDecimal.ZERO : rpt.getScrlostoutweight()).add(weight));
        }
        if (rpts.size() == 0) {
            rpt.setCompanyname(orgname);
            rpt.setSrname(room);
            rpt.setShname(house);
            rpt.setProductname(product);
            rpt.setSpecname(spename);
            rpt.setCreatetime(new Date());
            rpt.setStockunit(stockunit);
            rpt.setStockunitid(stockunitid);
            rpt.setGuid(IdUtils.fastSimpleUUID());
            rptStoreanalysisMapper.insertRptStoreanalysis(rpt);
        } else {
            rptStoreanalysisMapper.updateRptStoreanalysis(rpt);
        }
    }

    /**
     * 报废单组织，库房归类查询
     *
     * @param findDate
     * @return
     * @throws Exception
     */
    private List<Scrapapply> getDataScraptype(Date findDate) {
        Scrapapply witem = new Scrapapply();
        witem.setCreatetime(findDate);
        List<Scrapapply> items = scrapapplyMapper.rpt_scraptype(witem);
        return items;
    }

    /**
     * 报废单对应组织，库房所有查询
     *
     * @param findDate
     * @return
     * @throws Exception
     */
    private List<Scrapapply> getDataScrap(Date findDate, String orgguid, String srguid) {
        Scrapapply witem = new Scrapapply();
        witem.setCreatetime(findDate);
        witem.setOrgguid(orgguid);
        witem.setSrguid(srguid);
        List<Scrapapply> items = scrapapplyMapper.rpt_scrap(witem);
        return items;
    }

    /**
     * 加工报废重量统计
     *
     * @param scrapapplyids
     * @param orgguid
     * @param srguid
     * @param orgname
     * @param room
     * @param findDate
     * @param type
     * @return
     * @throws Exception
     */
    private Scrapapplyitem setDataScrapitem(String[] scrapapplyids, String orgguid, String srguid,
                                            String orgname, String room, Date findDate, int type) {
        Scrapapplyitem witem = new Scrapapplyitem();
        witem.setScrapapplyids(scrapapplyids);
        List<Scrapapplyitem> items = scrapapplyitemMapper.rpt_scrapitem(witem);
        for (int i = 0; i < items.size(); i++) {
            Scrapapplyitem item = items.get(i);
            if (null != item) {
                saveAndupdate(orgguid, srguid, item.getShguid(), item.getProductid()
                        , item.getSpecguid(), findDate, type, item.getWeight(), orgname, room
                        , item.getHousename(), item.getProduct(), item.getSpename(), 1, item.getStockunit(), item.getStockunitid());
            }
        }
        return witem;
    }


    /**
     * 腐烂、库损报废重量统计
     *
     * @param scrapapplyids
     * @param orgguid
     * @param srguid
     * @param orgname
     * @param room
     * @param findDate
     * @param type
     * @return
     * @throws Exception
     */
    private Scrapapplyitem setDataScrapitemL(String[] scrapapplyids, String orgguid, String srguid,
                                             String orgname, String room, Date findDate, int type) {
        Scrapapplyitem witem = new Scrapapplyitem();
        witem.setScrapapplyids(scrapapplyids);
        List<Scrapapplyitem> items = scrapapplyitemMapper.rpt_scrapitem(witem);
        for (int i = 0; i < items.size(); i++) {
            Scrapapplyitem item = items.get(i);
            if (null != item) {
                saveAndupdate(orgguid, srguid, item.getShguid(), item.getProductid()
                        , item.getSpecguid(), findDate, type, item.getWeight(), orgname, room
                        , item.getHousename(), item.getProduct(), item.getSpename(), 2, item.getStockunit(), item.getStockunitid());
            }
        }
        return witem;
    }
}
